package com.sfac.javaEE.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sfac.javaEE.common.Result;
import com.sfac.javaEE.entity.User;
import com.sfac.javaEE.service.UserService;
import com.sfac.javaEE.service.Impl.UserServiceImpl;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(value = {"/api/register"})
public class RegisterServlet extends HttpServlet {
    private ObjectMapper om = new ObjectMapper();
    private UserService userService = new UserServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        StringBuffer sb = new StringBuffer();
        String line = null;
        BufferedReader br = req.getReader();
        while ((line =  br.readLine()) != null) {
            sb.append(line);
        }
        User user = StringUtils.isNotBlank(sb) ?
                om.readValue(sb.toString(), User.class) :
                new User();

        Result<User> result = userService.insertUser(user);


        resp.setContentType("text/json;charset=UTF-8");
        PrintWriter pw = resp.getWriter();
        pw.write(om.writeValueAsString(result));
        pw.flush();
    }
}


